#!/usr/bin/perl

# Stop us from shooting outselves in the foot
use strict;
use warnings;
use FindBin qw($Bin);
use lib "$Bin";

# We are storing the configuration file in INI format
use File::Temp qw( tempdir );

# We need to parse emails
use Email::Simple;
use Email::MIME::Attachment::Stripper;
use Date::Format;
use DateTime::Format::Mail;

# Our own helper package
use MDBUtils;
use MDBAWS;

# Local sub routines
sub process_file;

# Configuration
my $config = MDBUtils::get_config();

# Our variables..
my $metadata;
my $response;
my $raw_input;

# Setup the environment
$metadata->{'rcvd_DateTime'} = DateTime->now();

# Concatinate the input to a single string
while (<STDIN>) {
    $raw_input = $raw_input . $_;
}

my $email    = Email::Simple->new($raw_input);
my $stripper = Email::MIME::Attachment::Stripper->new($raw_input);

# Extract the header metadata
$metadata->{'submitter'} = $email->header("From");
$metadata->{'sent_DateTime'} =
  DateTime::Format::Mail->parse_datetime( $email->header("Date") );

# Convert the timestamps to GMT timezone
$metadata->{'sent_DateTime'}->set_time_zone("GMT");
$metadata->{'rcvd_DateTime'}->set_time_zone("GMT");

# Extract the attachments
my $dir = tempdir( CLEANUP => 1 );
my @attachments = $stripper->attachments;

# For each attachment in the email...
for ( my $count = 0 ; $count < scalar(@attachments) ; $count++ ) {

    # Generate file location
    my $filename =
      File::Spec->catfile( $dir, $attachments[$count]{'filename'} );

    # Store the attachement in a file
    MDBUtils::string_to_file( $filename, $attachments[$count]{'payload'} );

    # Process the file
    process_file($filename);
}
print "DEBUG: Processed all the attachments\n\n";
exit;    # END OF PROGRAM

# Process the file
sub process_file {
    my $filename = shift
      or die("FUNCTION USAGE: process_file( filename );\n");

    print "DEBUG: process_file( " . $filename . " );\n";

    my $filetype = MDBUtils::filetype($filename);

    # What kind of content do we have?
    for ($filetype) {
        if (/Zip/) {
            my @filelist = MDBUtils::extract_archive_zip($filename);
            foreach my $file (@filelist) {
                process_file($file);
            }
        }
        elsif (/RAR/) {
            my @filelist = MDBUtils::extract_archive_rar($filename);
            foreach my $file (@filelist) {
                process_file($file);
            }
        }
        else {
            MDBAWS::store_sample( $filename, $metadata );
        }
    }
}
